import config from "@/config"

// openai 聊天接口，支持流式和非流式
export async function chat(
  { messages, model = config.model, stream = true } = {},
  onContent
) {
  const res = await fetch(config.BaseUrl + "/chat/completions", {
    method: "POST",
    headers: config.headers,
    body: JSON.stringify({
      stream,
      model,
      messages
    })
  })
  if (stream) {
    // 流式处理
    const reader = res.body.getReader()
    const decoder = new TextDecoder("utf-8")
    let result = ""
    while (true) {
      const { value, done } = await reader.read()
      if (done) break
      const chunk = decoder.decode(value, { stream: true })
      chunk.split("\n").forEach((line) => {
        if (line.startsWith("data:")) {
          try {
            const data = JSON.parse(
              line.replace("data: ", "").replace("data:", "")
            )
            const content = data.choices?.[0]?.delta?.content
            if (content) {
              result += content
              onContent && onContent(content, result) // 实时回调
            }
          } catch {}
        }
      })
    }
    return result
  } else {
    // 非流式
    const data = await res.json()
    return data
  }
}
